/*
 * File Name：DeviceUtils.java
 * Copyright：Copyright 2008-2014 CiWong.Inc. All Rights Reserved.
 * Description： DeviceUtils.java
 * Modify By：res-jxliu
 * Modify Date：2014-5-28
 * Modify Type：Add
 */
package com.ciwong.libs.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.http.conn.util.InetAddressUtils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

/**
 * 
 * 设备相关的处理类
 * 
 * @author res-jxliu
 * @version ciwong v.1.0 2014-5-28
 * @since ciwong v.1.0
 */
public class DeviceUtils
{
    private static final int MB = 1024 * 1024;

    private static Context mContext;

    /**
     * 设置上下文，供后面使用<br />
     * 注:此方法必须要在应用开启时或是调用内部方法前调用<br />
     * 否则可能会报空指针异常
     * 
     * @param context
     *            上下文
     */
    public static void setContext(Context context)
    {
        mContext = context;
    }

    /**
     * 
     * 获取上下文
     * 
     * @return mContext
     */
    public static Context getContext()
    {
        return mContext;
    }

    /**
     * 获取设备屏幕宽分辨率
     * 
     * 
     * 
     * @return 宽分辨率
     */
    public static int getScreenWdith()
    {
        Display display = getDisplay();
        return display.getWidth();
    }

    /**
     * 获取设备屏幕高分辨率
     * 
     * @return 高分辨率
     */
    public static int getScreenHeight()
    {
        Display display = getDisplay();
        return display.getHeight();
    }

    /**
     * 获取display
     * 
     * 
     * @return display
     */
    public static Display getDisplay()
    {
        Display display = ((WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        return display;
    }

    /**
     * 获取displaymetrics
     * 
     * 
     * @return displaymetrics
     */
    public static DisplayMetrics getDisPlayMetrics()
    {
        Display display = getDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getMetrics(dm);
        return dm;
    }

    /**
     * 获取屏幕dpi
     * 
     * 
     * @return dpi
     */
    public static int getScreenDpi()
    {
        DisplayMetrics dm = getDisPlayMetrics();
        return dm.densityDpi;
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     * 
     * @param pxValue
     *            px值
     * 
     * @return 转换成的值
     */
    public static int px2sp(float pxValue)
    {
        DisplayMetrics metrics = getDisPlayMetrics();
        return (int) (pxValue / metrics.scaledDensity + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     * 
     * @param spValue
     *            sp值
     * 
     * @return 转换成的值
     */
    public static int sp2px(float spValue)
    {
        DisplayMetrics metrics = getDisPlayMetrics();
        return (int) (spValue * metrics.scaledDensity + 0.5f);
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     * 
     * @param pxValue
     *            px值
     * 
     * @return 转换成的值
     */
    public static int px2dip(float pxValue)
    {
        DisplayMetrics dm = getDisPlayMetrics();
        return (int) (pxValue / dm.density + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     * 
     * @param dipValue
     *            dp值
     * 
     * @return 转换的值
     */
    public static int dip2px(float dipValue)
    {
        DisplayMetrics dm = getDisPlayMetrics();
        return (int) (dipValue * dm.density + 0.5f);
    }

    /**
     * 获取设备IP地址
     * 
     * @return 本机地址
     */
    public static String getLocalIpAddress()
    {
        try
        {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();)
            {
                NetworkInterface intf = en.nextElement();

                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();)
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(inetAddress
                                    .getHostAddress()))
                    {
                        String str = inetAddress.getHostAddress().toString();
                        if (str == null || "null".equals(str))
                        {
                            return "192.168.0.1";
                        }
                        return str;
                    }
                }
            }
        }
        catch (SocketException ex)
        {
            ex.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "192.168.0.1";

    }

    /**
     * 计算sdcard上的剩余空间
     * 
     * @return sdcard上的剩余空间,单位是MB
     */
    public static int freeSpaceOnSd()
    {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
                .getPath());
        double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
                .getBlockSize()) / MB;
        return (int) sdFreeMB;
    }

    /**
     * 
     * 判断SD卡是否可用
     * 
     * @return 是否可用
     */
    public static boolean isSDCARDEnable()
    {
        File cwFile = getCiwongRootFolder();
        if (getCiwongRootFolder().exists())
        {
            try
            {
                new FileOutputStream(cwFile.getAbsolutePath() + File.separator
                        + "a");
                return true;
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 习网根目录
     * 
     * @return 习网根目录
     */
    public static File getCiwongRootFolder()
    {
        File root = new File(getSDCardFolder(), "ciwong");
        if (!root.exists())
        {
            root.mkdirs();
        }
        return root;
    }

    /**
     * SD根目录
     * 
     * @return 习网根目录
     */
    public static File getSDCardFolder()
    {
        File root = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState()))
        {
            root = Environment.getExternalStorageDirectory();
        }
        else
        {
            root = Environment.getDataDirectory();
        }
        return root;
    }

}
